layui.define(['jquery', 'layer', 'func', 'conf'], function (exports) {
    const {jquery: $, conf} = layui;
    const layer = parent.layer;

    const Api = function (url, data = {}, method = 'POST', header = {}) {
        const params = conf.api.before({
            url: url,
            method: method,
            header: header,
            data: data
        });


        if (!params) {
            layer.msg('前置拦截器异常，无返回内容');
            return
        }

        var mockResult = Api.mock(params);
        if (typeof mockResult.then === "function") {
            return mockResult;
        }

        //直接返回promise对象
        if (typeof params.then === 'function') {
            return params;
        }

        return new Promise(function (resolve, reject) {
            params.success = function (response) {
                conf.api.after(response, params, resolve, reject);
            }
            params.error = function (xhr) {
                layer.msg('网络异常【' + xhr + '】，请求服务器失败');
                reject();
            }

            $.ajax(params)
        });
    }

    //获取页面的默认属性
    Api.assign = function (url, data = {}) {
        return new Promise(function (resolve, reject) {
            try {
                Api(url === true ? layui.router().href.split("?")[0] : url, data, 'get', {}).then(function (res) {
                    resolve(res.data);
                }).catch(function (res) {
                    resolve({});
                });
            } catch (e) {
                layer.msg("该页面为初始化数据异常，如无需初始化数据，请关闭相应得参数");
            }
        });
    }

    Api.mock = function (params) {
        if (!conf.api.mock.use) {
            return false;
        }

        var urlArray = params.url.split("/");
        urlArray[2] += conf.api.mock.path;
        urlArray[urlArray.length - 1] += ".json"

        return new Promise(function (resolve, reject) {
            $.getJSON(urlArray.join("/"), function (response) {
                conf.api.after(response, params, resolve, reject);
            });
        });
        
    }

    Api.json = function(file){
        return new Promise(function (resolve, reject) {
            $.getJSON(file, function (response) {
                resolve(response);
            });
        });
    }

    exports("api", Api);
});